package cn.project.servlet;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 点击邮箱内账号激活
 */
@WebServlet(name = "active",urlPatterns = {"/active"})
public class ActiveServlet  extends HttpServlet {

    private final static String PWD ="redis@WSX!QAZ1234XXX";
    private static Jedis redis =null;

    /**
     * 获取redis数据库连接
     */
    public ActiveServlet(){
        System.out.println("==========ActiveServlet");
        //实际上按面向对象的逻辑,此段应封装到Jredis的工具类中,
        //此处为了方便理解,暂不做封装

        //实例化连接池 ,JedisPool是一个线程安全的网络连接池
        JedisPoolConfig conf = new JedisPoolConfig();
        //设置连接池最大连接数和等待时常等参数
        //如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
        conf.setMaxActive(20);
        //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例，默认值也是8。
        conf.setMaxIdle(10);
        //等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时。如果超过等待时间，则直接抛出JedisConnectionException；
        conf.setMaxWait(1000);
        //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
        conf.setTestOnBorrow(true);

        //获取jedis实例
        JedisPool pool = new JedisPool(conf,
                "127.0.0.1",6379,2000,PWD);
        redis = pool.getResource();
//        String uname = jedis.get("str");  测试连接用
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("m");
        String activeCode = req.getParameter("c");
        String activeCodeFromCache = redis.get(email);
        if(activeCodeFromCache != null &&
                activeCodeFromCache.equals(activeCode)){
            //连接数据库、修改账号的状态为【已激活】
            //此处代码省略......
            req.setAttribute("msg", "账户激活成功!");
        }else
        {
            req.setAttribute("msg", "账户激活失败!");
        }
        RequestDispatcher rd = req.getRequestDispatcher("active.jsp");
        rd.forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
